import axios from "axios";
import errorHandle from "./errorHandle";
import { Message } from "element-ui";

class HttpRequest {
  // 获取基础配置
  getInsideConfig() {
    const config = {
      baseURL: process.env.VUE_APP_BASE_API || '/api',
      timeout: 10000
    }

    return config
  }

  // 设定拦截器
  interceptors(instance) {
    // 请求拦截器
    instance.interceptors.request.use((config) => {
      if (localStorage.getItem("token")) {
        config.headers.Authorization = localStorage.getItem("token");
      }
      return config;
    }, (err) => {
      errorHandle(err);
      return Promise.reject(err);
    }
    );

    // 响应拦截器
    instance.interceptors.response.use((res) => {
      if (res.status === 200) {
        let code = res.data.status;
        if (code === 200) {
          return Promise.resolve(res.data);
        } else {
          Message.error(res.data.msg);
          return Promise.reject(res);
        }
      } else {
        return Promise.reject(res);
      }
    }, (err) => {
      errorHandle(err);
      return Promise.reject(err);
    }
    );
  }

  // 创建实例
  request(options) {
    const instance = axios.create()
    const newOptions = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance)
    return instance(newOptions)
  }

  // get方法
  get(url, data) {
    const options = Object.assign({
      method: 'get',
      url,
    }, data)
    return this.request(options)
  }

  // post方法
  post(url, data) {
    return this.request({
      method: 'post',
      url,
      data
    })
  }

  // put方法
  put(url, data) {
    return this.request({
      method: 'put',
      url,
      data,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  }

  // delete方法
  delete(url, data) {
    const options = Object.assign({
      method: 'delete',
      url,
    }, data)
    return this.request(options)
  }
}

export default new HttpRequest();
